﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using CBMS.Common;
using CBMS.Interfaces;
using CBMS.Objects;
using CBMS.Business;
using CBMS.Resources;
using CBMS.View;
using CBMS.Models;

namespace CBMS.Uc
{
    public partial class usStaffList : BaseControl
    {
        #region Fields
        private string _sortField = "first_name";
        private string _sortExp = "ASC";
        private int _staffId = 0;
        private Boolean _IsAllowSort = true;
        private static IStaffRepository staffRes { get; set; }
        #endregion

        #region Init, Load
        public usStaffList()
        {
            InitializeComponent();
            pagerTop.PageSize = CommonFunction.GetDefaultPageSize();
            CommonFunction.MakeCheckBoxAbility(BaseFunctions.STAFF_ABILITY, clbAbility);
            CommonFunction.MakeComboBoxRole(cmbRole, true);
        }
        #endregion

        #region Methods
        private void SearchData()
        {
            string condition = "where 1=1";
            if (!string.IsNullOrEmpty(txtFirstName.Text))
                condition = condition + " and first_name like '%" + txtFirstName.Text.Trim() + "%'";
            if (!string.IsNullOrEmpty(txtLastName.Text))
                condition = condition + " and last_name like '%" + txtFirstName.Text.Trim() + "%'";
            if (!string.IsNullOrEmpty(cmbRole.SelectedValue.ToString()))
                condition = condition + " and r.role_code =" + cmbRole.SelectedValue.ToString() + "";
            //get ability   
            string ability = string.Empty;
            foreach (ItemDTO checkedItem in clbAbility.CheckedItems)
            {
                ability += checkedItem.Id.ToString() + ",";
            }
            if (!string.IsNullOrEmpty(ability))
            {
                ability = ability.Substring(0, ability.Length - 1);
                condition = condition + " and a.subcategory_id in(" + ability + ")";
            }
            int toTal = 0;
            IList<StaffDTO> lstObject = staffRes.SearchStaffsBySomeCondition(condition, pagerTop.PageIndex, pagerTop.PageSize, _sortField, _sortExp, ref toTal);
            try
            {
                dgvData.Rows.Clear();
                int indexDisable = 0;
                bool isDisableStaff = false;
                foreach (StaffDTO ps in lstObject)
                {
                    if (ps.StaffId == this.userLoginId)
                    {
                        isDisableStaff = true;
                    }
                    dgvData.Rows.Add(ps.StaffCode, ps.FirstName, ps.LastName, ps.UserName, ps.RoleName, ps.BranchName, ps.Email, ps.IsActive, ps.StaffId);
                    if (!isDisableStaff)
                        indexDisable++;
                }
                if (isDisableStaff)
                {
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgvData.Rows[indexDisable].Cells["colActive"];
                    checkCell.ReadOnly = true;
                    dgvData.Invalidate();
                }
            }
            catch
            {
            }
            pagerTop.TotalRecord = toTal;
            pagerTop.SelectRecord = lstObject.Count;
            pagerTop.SetPaging();
            if (pagerTop.TotalPage > 1)
                _IsAllowSort = true;
            else
                _IsAllowSort = false;

        }
        private int GetStaffSelect()
        {
            int result = int.MinValue;
            try
            {
                result = int.Parse(dgvData.CurrentRow.Cells["colId"].Value.ToString());
            }
            catch
            { }
            return result;
        }
        #endregion

        #region Events
        private void usStaffList_Load(object sender, EventArgs e)
        {
            staffRes = new StaffRepository();
            SearchData();
            cmbRole.Focus();
            cmbRole.Select();
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            pagerTop.PageIndex = 1;
            SearchData();
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            for (int i = 0; i < clbAbility.Items.Count; i++)
            {
                clbAbility.SetItemChecked(i, false);
            }
            cmbRole.SelectedIndex = 0;
            _sortField = "first_name";
            _sortExp = "ASC";
            pagerTop.PageIndex = 1;
            pagerTop.PageSize = CommonFunction.GetDefaultPageSize();
            SearchData();
        }
        private void pagerTop_PageIndexChanging(object obj, CustomControls.PageIndexChangeEventArgs e)
        {
            pagerTop.PageIndex = e.newPageIndex;
            SearchData();
        }
        private void pagerTop_PageSizeChanging(object obj, CustomControls.PageSizeChangeEventArgs e)
        {
            pagerTop.PageIndex = 1;
            pagerTop.PageSize = e.newPageSize;
            SearchData();
        }
        private void dgvData_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (!_IsAllowSort)
                return;
            string newSortField = dgvData.Columns[e.ColumnIndex].DataPropertyName;
            if (newSortField == _sortField)
            {
                if (_sortExp == "ASC")
                    _sortExp = "DESC";
                else _sortExp = "ASC";
            }
            else
            {
                _sortField = newSortField;
                _sortExp = "ASC";
            }
            SearchData();
        }
        private void dgvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string columName = dgvData.Columns[e.ColumnIndex].Name;
                string value = dgvData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                string id = dgvData.Rows[e.RowIndex].Cells["colId"].Value.ToString();
                if (columName == "colActive")
                {
                    int staffId = int.Parse(id);
                    if (staffId != this.userLoginId)
                    {
                        staffRes.ChangeActive(staffId);
                        SearchData();
                    }
                }
            }
            catch
            {
            }
        }
        private void tsmiEdit_Click(object sender, EventArgs e)
        {
            frmStaffDetail f = new frmStaffDetail(_staffId);
            Common.CommonFunction.ShowForm(f, this);
            if (f.DialogResult == DialogResult.OK)
            {
                SearchData();
            }
        }
        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            DialogResult confirm = MessageBox.Show(string.Format(ErrorMessages.I0002, "staff"), "Confirm delete", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (confirm == DialogResult.Yes)//delete
            {
                if (staffRes.DeleteStaff(_staffId))
                {
                    SearchData();
                }
            }
        }
        private void tsmiNew_Click(object sender, EventArgs e)
        {
            frmStaffDetail f = new frmStaffDetail();
            Common.CommonFunction.ShowForm(f, this);
            if (f.DialogResult == DialogResult.OK)
            {
                SearchData();
            }
        }
        private void cmsEmployee_Opening(object sender, CancelEventArgs e)
        {
            _staffId = GetStaffSelect();
            if (_staffId > 0)
            {
                tsmiNew.Visible = true;
                tsmiEdit.Visible = true;
                tsmiChangePass.Visible = true;
                tss3.Visible = true;
                tss1.Visible = true;
                tss2.Visible = true;
                if (this.userLoginId != _staffId)
                {
                    tsmiDelete.Visible = true;
                    tss4.Visible = true;

                }
                else
                {
                    tsmiDelete.Visible = false;
                    tss4.Visible = false;
                }

            }
            else
            {
                tsmiNew.Visible = true;
                tsmiEdit.Visible = false;
                tsmiDelete.Visible = false;
                tss3.Visible = false;
                tss4.Visible = false;
                tss1.Visible = true;
                tss2.Visible = true;
                tsmiChangePass.Visible = false;
            }
        }
        private void tsmiChangePass_Click(object sender, EventArgs e)
        {
            frmChangePassword f = new frmChangePassword(this._staffId);
            CommonFunction.ShowForm(f, this);
        }
        private void txtFirstName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                SearchData();
            }
        }
        private void txtLastName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                SearchData();
            }
        }
        #endregion
    }
}
